package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.vf.admin.client.common.ClientConstants.client_toke;

@Controller
@RequestMapping("/apptask")
public class AppTaskController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppQianDaoRecordService appQianDaoRecordService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService setupService;
    @Autowired
    AppTaskRecordService appTaskRecordService;
    @Autowired
    AppTaskService appTaskService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    AppSignConfigService appSignConfigService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppSignUserAlertService appSignUserAlertService;

    /**
     * @Description 用户签到操作
     * @Param: []
     * @return: com.vf.admin.common.entity.Result
     * @Author: ljx
     * @Date: 2021/07/23
     */
    @ResponseBody
    @RequestMapping("/qiandao")
    public Result qiandao() {
        try {
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);

            Integer signNode = 1;
            Integer signNodeNext = 1;

            //查询今天签到记录
            AppQianDaoRecord appQianDaoRecord = appQianDaoRecordService.getNow(user.getId());
            if (appQianDaoRecord != null) {
                return this.errorJSON("用户今日已经签到,不可重复签到!");
            } else {
                /**
                 * 如果今天没有签到
                 * 查询昨天的签到记录
                 * 如果昨天也没有签到，签到节点从1开始，如果昨天有签到，在昨天签到节点上+1
                 * 如果签到节点大于7，把节点重置
                 */
                AppQianDaoRecord yesterdayRecord = appQianDaoRecordService.getYesterday(userId);
                if (yesterdayRecord != null) {
                    signNode = yesterdayRecord.getSignNode() + 1;
                    if (signNode > 7) {
                        signNode = 1;
                    }
                } else {
                    signNode = 1;
                }

                signNodeNext = signNode + 1;
                if(signNodeNext == 7) {
                    signNodeNext = 1;
                }
            }

            Map<String, Object> data = new HashMap<>();
            String message = "";
            AppSignConfig signConfig = appSignConfigService.infoByDay(signNode);

            if (signConfig != null) {
                appMingXiZuanShiService.addMingxi(user.getId(), new BigDecimal(signConfig.getGiveDiamonds()), 1, "签到赠送奖励");
                appUserService.updateZuanShi(user.getId(), new BigDecimal(signConfig.getGiveDiamonds()));
                //添加签到记录
                AppQianDaoRecord qianDaoRecord = new AppQianDaoRecord();
                qianDaoRecord.setUserid(user.getId());
                qianDaoRecord.setNick(user.getNick());//签到用户名字
                qianDaoRecord.setPic(user.getPic());//用户头像
                qianDaoRecord.setUserid(user.getId());//用户表示
                qianDaoRecord.setPhone(user.getLoginname());
                qianDaoRecord.setJinbi(new BigDecimal(signConfig.getGiveDiamonds()));
                qianDaoRecord.setSignNode(signNode);
                qianDaoRecord.setStatus(1);
                qianDaoRecord.setIsFamily(0);
                qianDaoRecord.setCreatetime(new Date());
                appQianDaoRecordService.saveOrUpdate(qianDaoRecord);
                message = "+" + signConfig.getGiveDiamonds() + "钻石";

                appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SIGNON);

                signConfig = appSignConfigService.infoByDay(signNodeNext);
                String messageNext = "明天签到赠送" + signConfig.getGiveDiamonds() + "钻石";

                data.put("message", message);
                data.put("messageNext", messageNext);
            }
            return this.sucessJSON(data, "签到成功!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("用户签到操作接口异常" + e);
            return this.errorJSON("系统繁忙,请联系管理员!");
        }
    }

    /**
     * 签到列表
     *
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Result qiandaoList() {
        try {
            Map<String, Object> data = new HashMap<>();

            List<AppSignConfig> signConfigs = appSignConfigService.list();

            /**
             * onDay 连续签到天数
             * todaySigned 今天是否签到
             * node当前已签到节点
             *
             * 查询今天有没有签到
             * 今天没有签到查询昨天签到记录
             */
            AppQianDaoRecord qianDaoRecord = appQianDaoRecordService.getNow(getUserId());
            data.put("onDay", 0);
            data.put("node", 0);
            data.put("todaySigned", 0);
            if (qianDaoRecord != null) {
                data.put("onDay", qianDaoRecord.getSignNode());
                data.put("node", qianDaoRecord.getSignNode());
                data.put("todaySigned", 1);
            } else {
                qianDaoRecord = appQianDaoRecordService.getYesterday(getUserId());
                if (qianDaoRecord != null) {
                    data.put("onDay", qianDaoRecord.getSignNode());
                    data.put("node", qianDaoRecord.getSignNode());
                }
            }

            data.put("alert", 0);
            AppSignUserAlert userAlert = appSignUserAlertService.find(getUserId());
            if (userAlert != null && userAlert.getStatus() == 1) {
                data.put("alert", 1);
            }
            data.put("list", signConfigs);
            return this.sucessJSON(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("用户签到列表接口异常" + e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 切换每日签到提醒状态开关
     * @return
     */
    @ResponseBody
    @RequestMapping("/changeAlertStatus")
    public Result changeAlertStatus() {
        appSignUserAlertService.changeStatus(getUserId());

        return this.sucessJSON("成功");
    }

    /**
     * 获取今日签到提醒
     * @return
     */
    @ResponseBody
    @RequestMapping("/todayTaskAlert")
    public Result todayTaskAlert() {
        Map<String, Object> data = new HashMap();
        data.put("alert", 0);

        AppSignUserAlert userAlert = appSignUserAlertService.find(getUserId());
        if (userAlert != null && userAlert.getStatus() == 1) {
            AppQianDaoRecord appQianDaoRecord = appQianDaoRecordService.getNow(getUserId());
            if(appQianDaoRecord == null) {
                data.put("alert", 1);
            }
        }


        return this.sucessJSON(data);
    }

    /**
     * 获取个人任务列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/tasklist")
    public Result tasklist() {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            List<AppTask> appTaskList = appTaskService.findList();
            if (appTaskList != null && appTaskList.size() > 0) {
                Iterator<AppTask> iterator = appTaskList.iterator();
                while(iterator.hasNext()) {
                    AppTask task = iterator.next();
                    if(task.getType() == 1) {
                        Boolean completeOnce = appTaskRecordService.isCompleteOnce(userId, task.getTasknameEn());
                        task.setComplete(completeOnce);
                        //如果当前任务已完成 过滤掉不在前端显示
                        if(completeOnce) {
                            iterator.remove();
                        }
                    } else if (task.getType() == 2) {
                        Boolean completeOnce = appTaskRecordService.isCompleteToday(userId, task.getTasknameEn());
                        task.setComplete(completeOnce);
                    }
                }
            }
            return this.sucessJSON(appTaskList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("获取任务列表接口异常" + e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    public String getTimeInterval(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        String imptimeBegin = sdf.format(cal.getTime());
        // System.out.println("所在周星期一的日期：" + imptimeBegin);
        cal.add(Calendar.DATE, 6);
        String imptimeEnd = sdf.format(cal.getTime());
        // System.out.println("所在周星期日的日期：" + imptimeEnd);
        return imptimeBegin + "," + imptimeEnd;
    }

    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

}
